package nature.nano.control.script.parse;

import java.text.SimpleDateFormat;
import java.util.Date;

import nature.nano.component.PrimaryPipe;
import nature.nano.component.Strings;
import nature.nano.iface.Props;
import nature.nano.util.accepter.Printer;

public class VariableParser extends PrimaryPipe {
	
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat(Strings.compactTimeFormat);
	
	private class Variables {
		static final String today = "$TODAY";
		static final String yesterday = "$YESTERDAY";
		static final String beforeYesterday = "$BEFORE_YESTERDAY";
	}
	
	@Override
	public void anBegin(String type, Props props) {
		slot(Strings.output).onBegin(type, props);
	}

	@Override
	public void anContent(String content) {
		// TODO: 优化
		content = content.replace(Variables.today, dateFormat.format(new Date()));
		content = content.replace(Variables.yesterday, dateFormat.format(getdDateAfterDay(-1)));
		content = content.replace(Variables.beforeYesterday, dateFormat.format(getdDateAfterDay(-2)));
		
		slot(Strings.output).onContent(content);
	}

	@Override
	public void anEnd(String type) {
		slot(Strings.output).onEnd(type);
	}
	
	private Date getdDateAfterDay(int day) {
		Date now = new Date();
		long result = now.getTime() + day * 24 * 60 * 60 * 1000;
		return new Date(result);
	}
	
	public static void main(String[] args) {
		VariableParser parser = new VariableParser();
		parser.plug(Strings.output, new Printer());
		parser.onContent("sldjf$BEFORE_YESTERDAYLJSD");
	}
}
